<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Goods extends Base
{
    use SoftDeletes;

    // 数据表名
    protected $table = 'goods';

    // 数据主键
    protected $primaryKey = 'goods_id';

    // 隐藏字段
    protected $hidden = ['deleted_at', 'updated_at'];

    // 自动维护时间字段
    public $timestamps = true;

    /**
     * 货主（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function supplier() {
        return $this->hasOne('App\Models\Supplier', 'supplier_id', 'supplier_id');
    }

    /**
     * 商品竞标（一对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function bidGoods() {
        return $this->hasMany('App\Models\BidGoods', 'goods_id', 'goods_id')
            ->where('bid_goods.user_id', \Auth::id())
            ->leftJoin('bids', 'bids.bid_id', '=', 'bid_goods.bid_id')
            ->where('bids.status', 1)->select(['bid_goods.goods_id', 'bid_goods.bid_id', 'bid_goods.user_id', 'bid_goods.created_at', 'bid_goods.price']);
    }

    /**
     * 商品封面（一对一关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function cover() {
        return $this->hasOne('App\Models\GoodsFile', 'goods_id', 'goods_id')
            ->orderBy('type', 'desc')->select(['goods_id','type','path'])->whereIn('type', [1,2]);
    }

    /**
     * 商品视频（一对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function videos() {
        return $this->hasMany('App\Models\GoodsFile', 'goods_id', 'goods_id')
            ->where('type', 1);
    }

    /**
     * 商品图片（一对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images() {
        return $this->hasMany('App\Models\GoodsFile', 'goods_id', 'goods_id')
            ->where('type', 2);
    }

    /**
     * 商品文件（一对多关系）
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function files() {
        return $this->hasMany('App\Models\GoodsFile', 'goods_id', 'goods_id');
    }
}
